<?php
header('content-type:text/html;charset=utf-8');
$host = "localhost";
$user = "root";
$password = "";
$db = "library";
$mysqli = new mysqli($host, $user, $password, $db); //实例化mysqli对象，连接mysql数据库
if ($mysqli->connect_errno) {       
    die($mysqli->connect_error);
}
$mysqli->set_charset('utf8'); //设置字符集
//执行读取用户
getUser($mysqli);
//读取用户并显示
function getUser($mysqli)
{
    $sql = "SELECT id, password FROM user WHERE id = ? and password = ? ";
    $mysqli_stmt = $mysqli->prepare($sql);

    //定于要存值的变量
    $id = $_POST['id'];
    $password = $_POST['password'];

    $mysqli_stmt->bind_param('ss', $id, $password);

    if ($mysqli_stmt->execute()) {
        $id = null;
        $password = null;

        //bind_result() 绑定结果集中的值到变量
        $mysqli_stmt->bind_result($id, $password);
        //遍历结果集
        while ($mysqli_stmt->fetch()) {
            
            echo "<script>alert('恭喜您，登录成功！');window.location.href='all.php'</script>"; 
        }
    }
    if( $id != $_POST['id'] && $password != $_POST['password']){
       
        echo "<script>alert('用户名或密码错误，登录失败！');window.location.href='index.html'</script>"; 
    
    }
    else{
        echo "<script>alert('用户名或密码错误，登录失败！');window.location.href='index.html'</script>"; 
        
    }
    //释放结果集
    $mysqli_stmt->free_result();
    $mysqli_stmt->close();
}
$mysqli->close();

?>